package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.entity.SysUser;
import com.cy.pj.sys.mapper.SysMenuMapper;
import com.cy.pj.sys.mapper.SysRoleMenuMapper;
import com.cy.pj.sys.mapper.SysUserMapper;
import com.cy.pj.sys.mapper.SysUserRoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 设置凭证匹配器(与用户添加操作使用相同的加密算法)
     * 此方法的返回会告诉shiro框架，我们采用什么加密算法
     */
    @Override
    public void setCredentialsMatcher(
            CredentialsMatcher credentialsMatcher) {
        //构建凭证匹配对象
        HashedCredentialsMatcher cMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        cMatcher.setHashAlgorithmName("MD5");
        //设置加密次数
        cMatcher.setHashIterations(1);
        super.setCredentialsMatcher(cMatcher);
    }

    /**
     * 通过此方法完成认证数据的获取及封装,
     * 系统底层会将认证数据传递认证管理器，
     * 由认证管理器完成认证操作。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        //1.获取用户名(用户页面输入)
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        //2.基于用户名查询用户信息
        SysUser user = sysUserMapper.findUserByUserName(username);
        //3.判断用户是否存在
        if(user == null){
            throw new UnknownAccountException();
        }
        //4.判断用户是否已被禁用
        if(user.getValid() == 0){
            throw new LockedAccountException();
        }
        //5.提供第三个参数需要的盐值，将用户的盐值转换成ByteSource
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt().getBytes());
        //记住：构建什么对象要看方法的返回值
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,   //用户身份
                user.getPassword(), //已加密的密码
                credentialsSalt,    // 盐值，创建用户时给的盐值
                getName());         //为realm的名字

        //6.返回封装结果
        //返回值会传递给认证管理器(后续认证管理器会通过此信息完成认证操作)
        return info;
    }

    //=================授权管理实现===========================
    //通过此方法，完成授权信息的获取及封装
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        //1.获取登录用户信息，列如用户id
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
        Integer userId = user.getId();
        //2.基于用户id获取用户角色id(sys_user_roles)
        List<Integer> roleIds = sysUserRoleMapper.findRoleIdsByUserId(userId);
        if (roleIds == null || roleIds.size()==0){
            throw new AuthorizationException();
        }
        //3.基于角色id获取菜单id(sys_role_menus)
        Integer[] array = {};
        List<Integer> menuIds =
                sysRoleMenuMapper.findMenuIdsByRoleIds(roleIds.toArray(array));
        if (menuIds == null){
            throw new AuthorizationException();
        }
        //4.基于菜单id获取权限标识(sys_menus)
        List<String> permissions =
                sysMenuMapper.findPermissions(menuIds.toArray(array));
        //5.对权限标识信息进行封装并返回
        Set<String> set = new HashSet<>();
        for (String per : permissions) {
            if(!StringUtils.isEmpty(per)){
                set.add(per);
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);

        return info;//返回给授权管理器
    }


}
